<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Facades\Services\UserService;
use ValiDate;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    public function getUsers(){
    	return formatJsonResponse(UserService::getUsers());
    }

    public function addUser(Request $request){

    	$rules = [
    		'username' => 'required|unique:users,username',
    		'password' => 'required',
    		'role_id' => 'required|exists:roles,id',
            'last_name' => 'required',
            'first_name' => 'required'
    	];

    	ValiDate::valiDate($request,$rules);

    	UserService::addUser($request->only(['username','password','last_name','first_name']),$request->role_id);

    	return formatJsonResponse();
    }

    public function updateUser(Request $request){

        $rules = [
            'id' => 'required|exists:users,id',
            'username' => ['required',Rule::unique('users')->ignore($request->id,'id')],
            'role_id' => 'required|exists:roles,id',
            'last_name' => 'required',
            'first_name' => 'required'
        ];

        ValiDate::valiDate($request,$rules);

        UserService::updateUser($request->id,$request->only(['username','password','last_name','first_name']),$request->role_id);

        return formatJsonResponse();
    }

    public function updateOneSelf(Request $request)
    {
        $rules = [
            'last_name' => 'required',
            'first_name' => 'required',
        ];

        ValiDate::valiDate($request,$rules);

        $data = $request->all();

        UserService::updateOneSelf($data);

        return formatJsonResponse();
    }

    public function deleteUser(Request $request){
        $rules = [
            'id' => 'required|exists:users,id'
        ];

        ValiDate::valiDate($request,$rules);

        UserService::deleteUser($request->id);

        return formatJsonResponse();
    }

    public function getUser(Request $request){
        $rules = [
            'id' => 'required|exists:users,id'
        ];

        ValiDate::valiDate($request,$rules);

        return formatJsonResponse(UserService::getUser($request->id));
    }
}
